<template>
  <div id="pageMenuConfig">
    <v-container grid-list-xl fluid>
      <v-layout row wrap>
        <v-flex xs12>
          <v-container>
            <v-text-field
              v-model="search"
              id="search"
              key="search"
              label="搜索"
              append-icon="search"
              clearable
              hide-details
              single-line
              solo
              light
              @keyup.enter="init"
            />
          </v-container>
          <v-card class="mb-4">
            <v-toolbar color="primary lighten-1" dark flat dense cad>
              <v-toolbar-title class="subheading">菜单管理</v-toolbar-title>
              <v-spacer></v-spacer>
              <v-dialog v-model="dialog" persistent max-width="600px">
                <v-btn slot="activator" flat dark>
                  <v-icon>add</v-icon>&nbsp;新建
                </v-btn>
                <v-card>
                  <v-card-title>
                    <span class="headline">{{ formTitle }}</span>
                  </v-card-title>
                  <v-card-text>
                    <v-container grid-list-md>
                      <v-form>
                        <v-layout wrap>
                          <v-flex xs12 sm6>
                            <v-autocomplete
                              name="menu_type"
                              :items="menuTypes"
                              item-text="name"
                              item-value="value"
                              label="菜单类型"
                              v-validate="'required'"
                              data-vv-as="菜单类型"
                              data-vv-validate-on="blur"
                              :error="errors.has('menu_type')"
                              :error-messages="errors.collect('menu_type')"
                              v-model="editedItem.menu_type"
                              clearable
                            ></v-autocomplete>
                          </v-flex>
                          <v-flex xs12 sm6>
                            <v-select
                              name="menu_id"
                              :items="parentMenus"
                              item-text="name"
                              item-value="id"
                              label="父级菜单"
                              v-model="editedItem.menu_id"
                              clearable
                            ></v-select>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field
                              name="name"
                              label="菜单名*"
                              v-validate="'required'"
                              data-vv-as="标签名"
                              data-vv-validate-on="blur"
                              :error="errors.has('name')"
                              :error-messages="errors.collect('name')"
                              v-model="editedItem.name"
                            ></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="direct" label="链接" v-model="editedItem.direct"></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="order" label="排序" v-model="editedItem.order"></v-text-field>
                          </v-flex>
                          <v-flex xs12 sm6>
                            <v-switch
                              name="status"
                              :label="(editedItem.status ? `显示`: `隐藏`) + `菜单`"
                              v-model="editedItem.status"
                            ></v-switch>
                          </v-flex>
                        </v-layout>
                      </v-form>
                    </v-container>
                  </v-card-text>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" flat @click="close">取消</v-btn>
                    <v-btn color="blue darken-1" flat @click="save">保存</v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </v-toolbar>
            <v-divider></v-divider>
            <v-card-text>
              <v-data-table
                v-model="selected"
                :headers="headers"
                :items="menus"
                :pagination.sync="pagination"
                :total-items="totalMenus"
                :loading="loading"
                select-all
                item-key="id"
              >
                <template slot="headers" slot-scope="props">
                  <tr>
                    <th>
                      <v-checkbox
                        :input-value="props.all"
                        :indeterminate="props.indeterminate"
                        primary
                        hide-details
                        @click.stop="toggleAll"
                      ></v-checkbox>
                    </th>
                    <template v-for="header in props.headers">
                      <th v-if="header.sortable===false" :key="header.text">{{ header.text}}</th>
                      <th
                        v-else
                        :key="header.text"
                        :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '']"
                        @click="changeSort(header.value)"
                      >
                        <v-icon small>arrow_upward</v-icon>
                        {{ header.text }}
                      </th>
                    </template>
                  </tr>
                </template>
                <template slot="items" slot-scope="props">
                  <tr :active="props.selected" @click="props.selected = !props.selected">
                    <td>
                      <v-checkbox :input-value="props.selected" primary hide-details></v-checkbox>
                    </td>
                    <td class="text-xs-center">{{ props.item.id }}</td>
                    <td class="text-xs-center">{{ props.item.name }}</td>
                    <td class="text-xs-center">{{ getMenuType(props.item.menu_type).name }}</td>
                    <td class="text-xs-center">{{ props.item.order }}</td>
                    <td class="text-xs-center">
                      <v-btn
                        dark
                        small
                        depressed
                        :color="props.item.status ? `green`:`red`"
                      >{{ props.item.status ? `显示`:`隐藏` }}</v-btn>
                    </td>
                    <td class="text-xs-center">
                      <v-tooltip bottom>
                        <v-btn
                          flat
                          icon
                          color="green"
                          slot="activator"
                          @click="editItem(props.item)"
                        >
                          <v-icon small>edit</v-icon>
                        </v-btn>
                        <span>编辑</span>
                      </v-tooltip>
                      <v-tooltip bottom>
                        <v-btn
                          flat
                          icon
                          color="red"
                          slot="activator"
                          @click="deleteItem(props.item)"
                        >
                          <v-icon small>delete</v-icon>
                        </v-btn>
                        <span>删除</span>
                      </v-tooltip>
                    </td>
                  </tr>
                </template>
              </v-data-table>
              <div class="text-xs-left pt-2">
                <v-btn color="primary" dark @click="toggleReverse(menus)">反选</v-btn>
                <v-btn color="red" dark @click="deleteSelected">删除选中</v-btn>
              </div>
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import _ from 'lodash'
import { getAllMenus, createMenu, updateMenu, deleteMenu } from '@/api/resource/menus'
import Toast from '@/plugins/toast'
export default {
  name: 'menu-config',
  data: () => ({
    headers: [
      { text: 'ID', value: 'id' },
      { text: '标题', value: 'name' },
      { text: '类型', value: 'menu_type' },
      { text: '排序', value: 'order' },
      { text: '状态', value: 'status' },
      { text: '操作', value: 'action', sortable: false }
    ],
    dialog: false,
    loading: true,
    search: '',
    totalMenus: 0,
    menus: [],
    selected: [],
    pagination: {},
    editedIndex: -1,
    editedItem: {
      id: 0,
      menu_type: 0,
      menu_id: 0,
      name: '',
      direct: '',
      order: 999,
      status: true
    },
    defaultItem: {
      id: 0,
      menu_type: 0,
      menu_id: 0,
      name: '',
      direct: '',
      order: 999,
      status: true
    }
  }),
  computed: {
    formTitle () {
      return this.editedIndex === -1 ? '新建菜单' : '编辑菜单'
    },
    menuTypes () {
      return [ // todo:默认父级菜单
        { name: '空菜单', value: 0 },
        { name: '一级菜单', value: 1 },
        { name: '普通菜单', value: 2 },
        { name: '普通菜单（外链）', value: 3 }
      ]
    },
    parentMenus () {
      return _.filter(this.menus, (o) => {
        return _.includes([0, 1], o.menu_type)
      })
    }
  },
  watch: {
    dialog (val) {
      val || this.close()
    },
    pagination: {
      handler () {
        this.init()
      },
      deep: true
    }
  },
  methods: {
    toggleAll () {
      let _this = this
      if (_this.selected.length) _this.selected = []
      else _this.selected = _this.menus.slice()
    },
    toggleReverse (items) {
      this.selected = _.difference(items, this.selected)
    },
    changeSort (column) {
      let _this = this
      if (_this.pagination.sortBy === column) {
        _this.pagination.descending = !_this.pagination.descending
      } else {
        _this.pagination.sortBy = column
        _this.pagination.descending = false
      }
    },
    init () {
      let _this = this
      let params = {
        perPage: _this.pagination.rowsPerPage,
        page: _this.pagination.page,
        sortBy: ((_this.pagination.sortBy) ? _this.pagination.sortBy : `id`) + `,` + ((_this.pagination.descending === true) ? `desc` : `asc`)
      }
      if (_this.search) {
        params.search = _this.search
      }
      _this.loading = true
      getAllMenus({ 'params': params }).then(res => {
        _this.menus = res.data
        _this.totalMenus = res.meta.pagination.total
        _this.loading = false
      })
    },
    getMenuType (val) {
      return _.find(this.menuTypes, function (o) {
        return o.value === val
      })
    },
    editItem (item) {
      let _this = this
      _this.editedIndex = _this.menus.indexOf(item)
      _this.editedItem = Object.assign({}, item)
      _this.dialog = true
    },
    deleteItem (item) {
      let _this = this
      const index = _this.menus.indexOf(item)
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteMenu(item.id).then(res => {
            _this.menus.splice(index, 1)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    deleteSelected (items) {
      let _this = this
      let ids = []
      if (_this.selected.length === 0) {
        Toast.error({ msg: '请选择' })
        return false
      }
      _(_this.selected).forEach(function (value) {
        ids.push(value.id)
      })
      ids = ids.join()
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteMenu(ids).then(res => {
            _this.menus = _.difference(_this.menus, _this.selected)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    save () {
      let _this = this
      let index = _this.editedIndex
      let item = _this.editedItem
      _this.$validator.validateAll().then(result => {
        if (result) {
          if (index > -1) {
            if (!item.menu_id) {
              item.menu_id = 0
            }
            updateMenu(item.id, item).then(res => {
              Object.assign(_this.menus[index], item)
              Toast.success({ msg: '修改成功' })
            })
          } else {
            createMenu(item).then(res => {
              _this.menus.push(res.data)
              Toast.success({ msg: '添加成功' })
            })
          }
          _this.close()
        }
      })
    },
    close () {
      let _this = this
      _this.dialog = false
      _this.editedItem = Object.assign({}, _this.defaultItem)
      _this.editedIndex = -1
    }
  }
}
</script>
